<template>
	<el-row>
		<el-row>
			<el-button type="primary" icon="el-icon-caret-right" size="mini" @click="executeSql">执行</el-button>
			<el-button type="danger" icon="el-icon-warning" size="mini" @click="stopExec" :disabled="disableStop">停止</el-button>
		</el-row>
		<el-row>
			<textarea ref="myCode" v-model="code" class="code-sql"></textarea>
		</el-row>
		<el-row>
			<el-tabs type="border-card" v-model="currTab">
				<el-tab-pane label="消息" name="message">
					<textarea ref="msg" readonly></textarea>
				</el-tab-pane>
				<el-tab-pane label="结果" name="result">
					<el-table :height="tableHeight" :data="tableData" border stripe ref="table" v-loading="dataLoading"  element-loading-text = "数据正在加载中" element-loading-spinner="el-icon-loading">
						<el-table-column :key="column.name" v-for="column in columns" :prop="column.name" :label="column.name">
						</el-table-column>
					</el-table>
					<el-pagination
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						:current-page="pageNo"
						:page-sizes="[50, 100, 200, 300]"
						:page-size="pageSize"
						layout="total, sizes, prev, pager, next, jumper"
						:total="total">
					</el-pagination>
				</el-tab-pane>
			</el-tabs>
		</el-row>
	</el-row>
</template>

<script>
import "codemirror/theme/ambiance.css";
import "codemirror/lib/codemirror.css";
import "codemirror/addon/hint/show-hint.css";
import CodeMirror from "codemirror/lib/codemirror"
require("codemirror/mode/sql/sql");
require("codemirror/addon/hint/show-hint");
require("codemirror/addon/hint/sql-hint");

export default {
	name: "SqlPanel",
	components: {
	},
	data(){
		return {
			code: "",
			columns: [],
			editor: null,
			msgEditor: null,
			tableData: [],
			total: 0,
			pageNo: 1,
			pageSize: 50,
			currentSQL: '',
			tableHeight: 200,
			dataLoading: false,
			currTab: 'message',
			disableStop: true
		}
	},
	methods: {
		handleSizeChange(v){
			this.pageSize = v;
			this.executeSql();
		},
		handleCurrentChange(v){
			this.pageNo = v;
			this.executeSql();
		},
		stopExec(){

		},
		async executeSql(){
			let selectSQL = window.getSelection().toString();
			if(selectSQL.length === 0 || selectSQL === ''){
				selectSQL = this.editor.getValue();
			}
			this.currentSQL = selectSQL;
			this.disableStop = false;
			if(this.currentSQL !== '' && this.currentSQL.length > 0){
				this.dataLoading = true;
				const result = await this.$http.post('/db/execute',{
					sql: this.currentSQL,
					pageNo: this.pageNo,
					pageSize: this.pageSize,
					db: this.$store.state.database,
					resourceId: this.$store.state.dbInstance
				});
				if(result.code === 500){
					this.dataLoading = false;
					this.msgEditor.setValue(result.message);
					this.currTab = 'message';
					setTimeout(() => {
						this.msgEditor.refresh();
					}, 500);
					this.disableStop = true;
				}else {
					this.currTab = 'result';
					this.msgEditor.setValue('');
					this.dataLoading = false;
					this.columns = result.data.columns;
					this.tableData = result.data.rows;
					this.total = result.data.total;
					this.disableStop = true;
				}
			}else{
				this.$message.error("执行的sql不能为空!");
			}

		}
	},
	mounted() {
		this.editor = CodeMirror.fromTextArea(this.$refs.myCode, {
			mode: "text/x-mysql",
			indentWithTabs: true,
			smartIndent: true,
			lineWrapping: true,
			lineNumbers: true,
			matchBrackets: true,
			styleActiveLine: true,
			autoCloseBrackets: true,
			autofocus: true,
			extraKeys: {'Tab': 'autocomplete'},
			hintOptions: {
				tables: {
					users: ['name', 'score', 'birthDate'],
					countries: ['name', 'population', 'size']
				}
			}
		});
		this.editor.on("keyup", function (cm, event) {
			if (!cm.state.completionActive &&
				((event.keyCode >= 65 && event.keyCode <= 90 ) || event.keyCode === 52 || event.keyCode === 219 || event.keyCode === 190)) {
				CodeMirror.commands.autocomplete(cm, null, {completeSingle: false});
			}
		});
		this.editor.refresh();

		this.msgEditor = CodeMirror.fromTextArea(this.$refs.msg, {
			mode: "text/x-mysql",
			indentWithTabs: true,
			smartIndent: true,
			lineWrapping: true,
			lineNumbers: true,
			styleActiveLine: true,
			autoCloseBrackets: true
		});
		this.msgEditor.refresh();
		this.$nextTick(function () {
			this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 460;
		});

		this.currTab = 'result';
	}
}
</script>
